import java.util.Objects;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:定时器
 * User:岁亮亮
 * Date:2024-03-26
 * TIME:19:21
 */
class MyTimerTask implements Comparable<MyTimerTask>{
    //定义一个timer 记录下任务的绝对时间 ms级别
    private long timer;
    //内部持有runnable
    private Runnable runnable;
    public void run(){
        runnable.run();
    }



    //构造方法
    public MyTimerTask(Runnable runnable,long display){
        this.runnable = runnable;
        //timer 是记录绝对时间的
        this.timer = System.currentTimeMillis()+display;
    }
    public long getTimer() {
        return timer;
    }
    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.timer-o.timer);
    }
}
class MyTimer{
    //定义一个扫描线程 扫描优先级队列中的任务到时间了 九去执行
    private Thread thread = null;
    Object locker = new Object();

    //优先级队列 组织任务
    PriorityQueue<MyTimerTask> queue = new PriorityQueue();

    //schdule方法
    public void schedule(Runnable runnable,long display){
        synchronized (locker){
            MyTimerTask task = new MyTimerTask(runnable,display);
            queue.offer(task);
            locker.notify();
        }

    }
    //构造方法 执行顶一个线程
    public MyTimer(){
        thread = new Thread(() ->{
            while (true){//线程安全问题 thread 线程一边执行和删除队首元素 而main主线程在执行任务增加元素同时对同一睢县进行修改
                //刚开始队列为哦空时
                try {
                    synchronized(locker){
                        if(queue.isEmpty()){
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        long curtimer = System.currentTimeMillis();
                        if( curtimer >= task.getTimer()){
                            queue.poll();
                            task.run();
                        }
                        else {
                            locker.wait(task.getTimer()-curtimer);
                        }
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }


            }
        });
        thread.start();
    }
}
public class TestTimer {
    public static void main(String[] args) {
        MyTimer timer1 = new MyTimer();
        timer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 5000ms");
            }
        },5000);
        MyTimer timer2 = new MyTimer();
        timer2.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000ms");
            }
        },3000);
        MyTimer timer3 = new MyTimer();
        timer3.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000ms");
            }
        },1000);
        System.out.println("hello main");
    }
}
